<%@ include file="/taglibs.jsp"%>

<head>
    <title><c:if test="${empty param.id}">
		<fmt:message key="workflow.addform.title" />
	</c:if> <c:if test="${not empty param.id}">
		<fmt:message key="workflow.editform.title" />
	</c:if></title>
	
    <style type="text/css">
    	.up, .down, .rm {
    		margin-left: 5px;
    	}
    	.inputElm {
    		text-align: center !important;
    	}
    </style>
</head>

<br>


<fieldset>
<s:textfield key="processStatus.status" name="stepName" size="50"></s:textfield>

<button type="button" class="button" id="search">
				<fmt:message key="button.search.title"></fmt:message>
				<img src="${ctx}/images/btn_search.png" align="left" height="20" width="20">
			</button>
<br>

<display:table name="processes" class="table" requestURI="" htmlId="processes" export="false" pagesize="10">
    <display:column property="status" href="editProcessStatus.html" media="html" paramId="id" paramProperty="id"  titleKey="processStatus.status"/>
    <display:column titleKey="select.default.value" style="width:30px;"></display:column>
</display:table>

</fieldset>


<s:form name="workflowEditForm" action="save_workflow" method="post" validate="true" theme="simple">
<s:hidden name="workflow.id" value="%{workflow.id}" theme="simple"/>
<%-- <s:hidden id="workflowName" key="workflow.name"/> --%>
<fieldset>
<s:text name="workflow.name"></s:text>
<s:if test="!used">
	<s:textfield key="workflow.name" id="workflowNameFake" size="70" required="true" theme="simple" cssStyle="margin-bottom: 10px;"/>
	
</s:if>
<s:else>
	<strong><s:property value="workflow.name"/></strong>
	<p></p>
</s:else>
		<%-- <legend><s:text name="workflow.process.status.selected"></s:text></legend> --%>
		<display:table name="lstSelectedProcessStatus" class="table" requestURI="" id="sps" export="false">
		    	<display:column property="status" media="html"
		         		titleKey="processStatus.status" escapeXml="true" />
			    <display:column titleKey="processStatus.days" class="inputElm" style="width:50px;">
			    		<s:if test="!used">
			    			<input type="text" size="4" name="processTime" value="${sps.workflowProcess.processTime}">
			    		</s:if>
			    		<s:else>
			    			${sps.workflowProcess.processTime}
			    		</s:else>
			    </display:column>
			    <display:column titleKey="fileStatus.status" class="inputElm">
			    		 <s:if test="!used">
					    	<s:set scope="request" value="lstFileStatus" var="lstFileStatus"/>
					    	<select name="fileStatus">
					    		<c:forEach var="fs" items="${lstFileStatus}">
					    			<option value="${fs.id}" ${sps.workflowProcess.fileStatus.id eq fs.id ? "selected='selected'" : ""}>${fs.status}</option>
					    		</c:forEach>
					    	</select>
				    	</s:if>
				    	<s:else>
				    		${sps.workflowProcess.fileStatus.status}
				    	</s:else>
			    </display:column>
			    <display:column titleKey="processStatus.lineDept" class="inputElm" style="width:30px;">
				    	<c:if test="${sps.workflowProcess.lineDept}">
				    		<input type='hidden' name='lineDept' value='true'>
				    		<input type="radio" name='lineDeptRadio' <s:if test="used">disabled="disabled"</s:if> checked="checked" class='lineDept'>
				    	</c:if>
				    	<c:if test="${!sps.workflowProcess.lineDept}">
				    		<input type='hidden' name='lineDept' value='false'>
				    		<input type="radio" name='lineDeptRadio' <s:if test="used">disabled="disabled"</s:if> class='lineDept'>
				    	</c:if>
			    </display:column>
			    <display:column style="width:90px;" titleKey="category.function">
			    	<input type="hidden" name="processStatus" value="${sps.id}">
			    	<c:if test="${!sps.used}">
				    	<a href="javascript:void(0)" class="rm"><img src="${ctx}/images/btn_remove.png" width="20"></a>
			    		<a href="javascript:void(0)" class="up"><img src="${ctx}/images/btn_up.png" width="20"></a>
				    	<a href="javascript:void(0)" class="down"><img src="${ctx}/images/btn_down.png" width="20"></a>
				    </c:if>
			    </display:column>
		</display:table>
</fieldset>

<tr>
    <td colspan="2">
	    <s:if test="!used">
	    	<s:a href="javascript:void(0)" id="save">
				<img src="${ctx}/images/btn_save_link.png">
			</s:a>
		</s:if>	
	    <c:if test="${not empty param.id and workflow.deletable}">
	    	<s:url action="delete_workflow" var="delURL">
	    		<s:param name="id" value="%{workflow.id}"></s:param>
	    	</s:url>
	    	<s:a href="%{delURL}" id="delete">
				<img src="${ctx}/images/btn_delete_link.png">
			</s:a>
    	</c:if>
        <s:a action="workflows" id="cancel">
			<img src="${ctx}/images/btn_cancel_link.png">
		</s:a>
    </td>
</tr>

</s:form>
<s:if test="!used">
<s:select list='lstFileStatus' id="fileStatusElm" listKey="id" listValue="status" cssStyle="visibility: hidden;" theme="simple"/>
<script type="text/javascript">

 $(document).ready(function() {
	$('#search').click( function(){
		if ($('input[name="stepName"]').val() != "") {
			$.blockUI({ message: ajaxAnimation });
			$.ajax({
			  url: '${ctx}/get-process-step.html',
			  data : {'stepName' : Url.encode($('input[name="stepName"]').val()), 'selectedStep':$('input[name="processStatus"]').val()},
			  dataType : 'text/html',
			  success: function(data) {
					$('#processes tbody').html(data);
			  }
			});
		} 
	});
	
	
}); 
 
 function searching(str){
	 
	 if ($('input[name="stepName"]').val() != "") {
			$.ajax({
			  url: '${ctx}/get-process-step.html',
			  data : {'stepName' : Url.encode($('input[name="stepName"]').val())},
			  dataType : 'text/html',
			  success: function(data) {
					$('#processes tbody').html(data);
			  }
			});
		} 
	 
 }

	$('input[name="processTime"]').live('keypress', $.NumberUtils.acceptFloatOnly);
	$('#save').click(function(){
		$.blockUI({ message: '<img src="${ctx}/images/busy.gif" />...' });
		$('#workflowName').val($('#workflowNameFake').val());
		$.ajax({
		  type: 'POST',
		  url: $('form').attr('action') + '?struts.enableJSONValidation=true&struts.validateOnly=true',
		  data: $('form').serialize(),
		  dataType: "json",
		  success: function(json){
			 var errorsObject = $.StrutsUtils.getValidationErrors(json);
			 if(errorsObject.fieldErrors) {
				 $.StrutsUtils.showValidationErrors($('form'), errorsObject);
		     } else if(errorsObject.errors) {
				 $.StrutsUtils.showValidationErrors($('form'), errorsObject);
		     } else {
		       //good to go, regular submit
		       $('form').submit();
		     }
		  },
		  dataType: "text/html"
		});
	});
		
	var addHandler = function(){
		if ($('#sps tbody').children().find('td').attr('colspan') > 1) {
			$('#sps tbody').empty();
		}
		
		var tr = $(this).parents('tr').clone();
		tr.appendTo($('#sps tbody'));
		
		var input = tr.find('.inputElm');
		var processTime = "<td class='inputElm'><input type='text' name='processTime' size='4'></td>";
		var fileStatus = $('#fileStatusElm').clone().attr('style', '').attr('name', 'fileStatus').wrap('<td class="inputElm"></td>').parent().wrap('<div></div>').parent().html();
		var lineDept = "<td class='inputElm'><input type='hidden' name='lineDept' value='false'><input type='radio' name='lineDeptRadio' class='lineDept'></td>";
		
		if (input.size() == 0) {
			$(processTime + fileStatus + lineDept).insertBefore(tr.find('td:last'));
		} else {
			input.show();
		}
		
		tr.find('a:first').html('<img src="${ctx}/images/btn_remove.png" width="20">').attr('class', 'rm').click(rmHandler);
		
		var up = $('<a href="javascript:void(0)" class="up"><img src="${ctx}/images/btn_up.png" width="20"></a>').click(upDownHandler);
		var down = $('<a href="javascript:void(0)" class="down"><img src="${ctx}/images/btn_down.png" width="20"></a>').click(upDownHandler);
		
		up.insertAfter(tr.find('a'));
		down.insertAfter(up);
		
		$(this).parents('tr').remove();
		emptyHandler();
	};
	
	var rmHandler = function(){
		if ($('#sps tbody').children().find('td').attr('colspan') > 1) {
			$('#sps tbody').empty();
		}
		if ($('#processes tbody').children().find('td').attr('colspan') > 1) {
			$('#processes tbody').empty();
		}
		
		/* var tr_rm = $(this).parent().parent().clone();
		tr_rm.appendTo($('#processes tbody')); */
		
		$(this).parent().parent().remove();
		tr_rm.find('.inputElm').hide();
		tr_rm.find('a:first').html('<img src="${ctx}/images/btn_select.png" width="20">').attr('class', 'add').click(addHandler).siblings('a').remove();
		
		emptyHandler();
	};
	
	function emptyHandler() {
		if ($('#sps tbody').children().size() == 0) {
			$('#sps tbody').append('<tr><td colspan="5"><s:text name="basic.msg.empty_list"></s:text></td></tr>');
		}
		if ($('#processes tbody').children().size() == 0) {
			$('#processes tbody').append('<tr><td colspan="2"><s:text name="basic.msg.empty_list"></s:text></td></tr>');
		}
	}
	
	var upDownHandler = function(){
		var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
        	if (row.prev().find('input').size() != 0) {
            	row.insertBefore(row.prev());
        	}
        } else {
            row.insertAfter(row.next());
        }
	};

	$('.add').click(addHandler);
	$('.rm').click(rmHandler);
	$('.up,.down').click(upDownHandler);
	$('.lineDept').live('click', function(){$('input[name="lineDept"]').val('false'); $(this).prev().val('true');});
	
	$('form').submit(function() {
		$('#processes input').remove();
	});
	
	
	
	
	
	
	
	
	/**
	*
	*  URL encode / decode
	*  http://www.webtoolkit.info/
	*
	**/
	 
	var Url = {
	 
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},
	 
		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
	 
			return string;
		}
	 
	}
</script>
</s:if>
